package com.logistics.modules.sys.service.impl;


import com.logistics.common.utils.R;
import com.logistics.modules.sys.entity.SysUserEntity;
import com.logistics.modules.sys.form.SysLoginForm;
import com.logistics.modules.sys.service.SysLoginService;
import com.logistics.modules.sys.service.SysUserService;
import com.logistics.modules.sys.service.SysUserTokenService;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 系统登录服务impl
 *
 * @author 水穷处云起时
 * @date 2022/05/02
 */
@Service
public class SysLoginServiceImpl implements SysLoginService {

    /**
     * 系统用户服务
     */
    @Autowired
    private SysUserService sysUserService;

    /**
     * 系统用户令牌服务
     */
    @Autowired
    private SysUserTokenService sysUserTokenService;

    /**
     * 登录
     *
     * @return {@link R}
     */
    @Override
    public R login(SysLoginForm form) {
        //用户信息
        SysUserEntity user = sysUserService.queryByUserName(form.getUsernamea());

        //账号不存在、密码错误
        if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
            return R.error("账号或密码不正确");
        }

        //账号锁定
        if(user.getStatus() == 0){
            return R.error("账号已被锁定,请联系管理员");
        }

        //生成token，并保存到数据库
        R r = sysUserTokenService.createToken(user.getUserId());

        return r;
    }
}
